package cn.billy.system.service.impl;

import cn.billy.system.domain.Role;
import cn.billy.system.mapper.RoleMapper;
import cn.billy.system.service.IRoleService;
import cn.billy.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author billy
 * @since 2022-07-11
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void save(Role role) {
        roleMapper.add(role);
        initRelationTableSave(role);
    }

    public void initRelationTableSave(Role role){
        if (role.getId() != null) {
            roleMapper.saveRoleMenu(role.getId(), role.getMenus());
            roleMapper.saveRolePermission(role.getId(), role.getPermissions());
        }
    }

    public void initRelationTableUpdate(Role role){
        roleMapper.removeRoleMenu(role.getId());
        roleMapper.removeRolePermission(role.getId());
        if (role.getId() != null) {
            roleMapper.saveRoleMenu(role.getId(), role.getMenus());
            roleMapper.saveRolePermission(role.getId(), role.getPermissions());
        }
    }

    public void initRelationTableRemove(Long id){
        roleMapper.removeRoleMenu(id);
        roleMapper.removeRolePermission(id);

    }

    @Override
    public void update(Role role) {
        roleMapper.update(role);
        initRelationTableUpdate(role);
    }

    @Override
    public void remove(Long id) {
        initRelationTableRemove(id);
        roleMapper.remove(id);

    }
}
